package org.jmc.refmanager.security;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.authentication.encoding.PasswordEncoder;

public class DbPasswordInitializer extends JdbcDaoSupport {
	@Resource(name = "passwordEncoder")
	private PasswordEncoder passwordEncoder;

	public void secureDatabase() {
		getJdbcTemplate().query("select username, password from users where init=false",
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
						String username = rs.getString(1);
						String password = rs.getString(2);
						String encodedPassword = passwordEncoder.encodePassword(password, null);
						getJdbcTemplate()
								.update("update users set password = ?, init = ? where username = ?",
										encodedPassword, true, username);
						logger.debug("Updating password for username: "
								+ username + " to: " + encodedPassword);
					}
				});
	}

}
